package com.heba.greenmulu.message;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.diary.ItemImageTagObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.GlideUtil;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息傳送
 * Created by jason on 2020/1/15.
 */
public class ItemMessageSendActivity extends BaseActivity {

    private EditText et_search;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<UserObject> list;

    private String keyword = "";  //搜索關鍵詞

    private String sendTitle; //傳送對話框顯示標題
    private int type;   //判斷傳送的類型 0:傳送產品  1:傳送賬戶  3:傳送日記  4:图片标记用户选择
    private int imagePostion; //type=4，图片标记用户时需要用到 记录是哪张图片需要标记用户标签
    private int tagImagePos_x;  //type=4，图片标记用户 x轴坐标位置
    private int tagImagePos_y;  //type=4，图片标记用户 y轴坐标位置
    private String resourceID;  //傳送ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_send);
        initTopbar();
        findViewById();
        initView();
        getAddressListData();
    }

    @Override
    protected void findViewById() {
        et_search = findViewById(R.id.et_search);
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            type = bundle.getInt(CommonConfig.TYPE, 0);
            resourceID = bundle.getString(CommonConfig.MESSAGE_ID, "");
            imagePostion = bundle.getInt(CommonConfig.POSITION, 0);
            tagImagePos_x = bundle.getInt(CommonConfig.TAG_IMAGE_POS_X, 0);
            tagImagePos_y = bundle.getInt(CommonConfig.TAG_IMAGE_POS_Y, 0);
        }

        txt_title.setText(getResources().getString(R.string.message_send));

        /**
         * 显示对应文字
         */
        switch (type) {
            case CommonConfig.TYPE_SEND_PRODUCT:
                sendTitle = this.getResources().getString(R.string.message_send_product);
                break;
            case CommonConfig.TYPE_SEND_USER:
                sendTitle = this.getResources().getString(R.string.message_send_user);
                break;
            case CommonConfig.TYPE_SEND_DIARY:
                sendTitle = this.getResources().getString(R.string.message_send_diary);
                break;
            case CommonConfig.TYPE_IMAGE_TAG:
                txt_title.setText(getResources().getString(R.string.diary_image_tag));
                sendTitle = "";
                break;
            default:
                break;
        }

        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<UserObject>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_message_user_row;
            }

            @Override
            public void convert(VH holder, UserObject data, int position) {
                GlideUtil.loadImageWithPlaceHolderID(ItemMessageSendActivity.this, data.getIcon(), holder.getView(R.id.iv_avatar), R.drawable.icon_head_portrait);
                holder.setText(R.id.tv_name, data.getAccount());

                /**
                 * 傳送消息
                 */
                holder.itemView.setOnClickListener(v -> {

                    if (type == CommonConfig.TYPE_IMAGE_TAG) {
                        //图片标记用户选择，用EventBus通知更新
                        MessageEvent event = new MessageEvent();
                        ItemImageTagObject tagObject = new ItemImageTagObject();
                        tagObject.setUserID(data.getUserID());
                        tagObject.setUserName(data.getAccount());
                        tagObject.setX(tagImagePos_x);
                        tagObject.setY(tagImagePos_y);
                        event.setEvent(CommonConfig.EVENT_IMAGE_TAG);
                        event.setPosition(imagePostion);
                        event.setImageTagObject(tagObject);
                        EventBus.getDefault().post(event);
                        finishActivity();
                        return;
                    }

                    /**
                     * 彈出對話框顯示
                     */
                    new CustomDialogView(new CustomDialogView.OnSendMessageClickListener() {
                        @Override
                        public void onSendClick() {
                            /**
                             * 調用傳送訊息接口
                             */
                            progressDialog.show();
                            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                @Override
                                public void Success() {
                                    progressDialog.dismiss();
                                    ToastShow.displayToast(ItemMessageSendActivity.this, getResources().getString(R.string.message_send_success));
                                    finishActivity();
                                }

                                @Override
                                public void Fail(String error) {
                                    progressDialog.dismiss();
                                    ToastShow.displayToast(ItemMessageSendActivity.this, getResources().getString(R.string.message_send_failure));
                                }
                            }).sendMessage(ItemMessageSendActivity.this, resourceID, type, data.getUserID());
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    }).showDialogSendMessage(ItemMessageSendActivity.this, sendTitle, data);

                });
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        /**
         * 搜索用戶
         */
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = et_search.getText().toString();
                    getAddressListData();
                }
                return false;
            }
        });

        /**
         * 监听搜索
         */
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = s.toString();
                getAddressListData();
            }
        });

    }

    /**
     * 獲取通訊錄列表
     */
    private void getAddressListData() {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Username", keyword);
        client.get(Cfg.BaseUrl + "/Diary/AddressBook", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        list.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<UserObject> userObjects = new Gson().fromJson(array.toString(), new TypeToken<List<UserObject>>() {
                                }.getType());
                                list.addAll(list.size(), userObjects);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 刷新數據
                         */
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                    }

                });
    }

}
